package utilities;

import java.awt.image.BufferedImage;
/**
 *
 * Class handling the animations
 */

public class ImagePlayer
{
    private String imName;
    private ImageLoader imLoader;

    private int showPeriod;
    private int numImages;
    private int imPosition;
    private int animPeriod;
    
    private long animTotal;

    private boolean isRepeating;
    private boolean ticksIgnored;

    private double seqDuration;

    private ImagePlayerWatcher watcher=null;

    public ImagePlayer(String name,int ap,double d,boolean bool,ImageLoader im)
    {
        imName=name;
        animPeriod=ap;
        seqDuration=d;
        isRepeating=bool;
        imLoader=im;

        animTotal=0L;

        if (seqDuration<0.5)
        {
            System.out.println("Warning: minimum sequence duration is 0.5 sec.");
            seqDuration=0.5;
        }

        if (!imLoader.isLoaded(imName))
        {
            System.out.println(imName + " is not known by the ImageLoader");
            numImages=0;
            imPosition=-1;
            ticksIgnored=true;
        }
        else
        {
            numImages=imLoader.numberOfImages(imName);
            imPosition=0;
            ticksIgnored=false;
            showPeriod=(int)(1000*seqDuration/numImages);
        }
    }

    public void updateTick()
    {
        if (!ticksIgnored)
        {
            animTotal=(animTotal + animPeriod)%(long)(1000 * seqDuration);
            imPosition=(int)(animTotal/showPeriod);
            if ((imPosition==numImages-1)&&(!isRepeating))
            {
                ticksIgnored=true;
                if (watcher!=null)
                    watcher.sequenceEnded(imName);
            }
        }
    }

    public void stop()
    {
        ticksIgnored = true;
    }

    public BufferedImage getCurrentImage()
    {
        if (numImages!=0)
            return imLoader.getImage(imName,imPosition);
        else
            return null;
    }

    public void setWatcher(ImagePlayerWatcher w)
    {
        watcher=w;
    }

    public void resume()
    {
        if (numImages!=0)
            ticksIgnored = false;
    }

    public boolean atSequenceEnd()
    {
        return ((imPosition==numImages-1)&&(!isRepeating));
    }

    public void restart(int imPosn)
    {
        if (numImages != 0)
        {
            if ((imPosn<0)||(imPosn>numImages-1))
            {
                imPosn = 0;
            }

            imPosition=imPosn;
            animTotal=(long)imPosition*showPeriod;
            ticksIgnored=false;
        }
    }

}
